package com.heima.app.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {

    /**
     *  1.获取request和response对象
     *  2.判断是否是登录
     *  3.获取token
     *  4.判断token是否存在
     *  5.判断token是否有效
     *  6.放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (request.getURI().getPath().contains("/login")){
            //为登录请求,不拦截放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        Claims claimsBody = null;
        try {
            claimsBody = AppJwtUtil.getClaimsBody(token);
            //-1：有效，0：有效，1：过期，2：过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2){
                //token无效
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }



            Object userId = claimsBody.get("id");

            //将用户id存入请求头中
            ServerHttpRequest request1 = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId",userId.toString());
            }).build();
            //重置请求
            exchange.mutate().request(request1).build();





        } catch (Exception e) {
           e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
